package com.triptogether.trip.fragments;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.triptogether.R;
import com.triptogether.baseclasses.BaseFragment;
import com.triptogether.trip.adapters.TripTabsPagerAdapter;

public class TripMainFragment extends BaseFragment {

	public static final String ARG_TRIP_ID = "ARG_TRIP_ID";
	
	private TripTabsPagerAdapter tripTabsStatePagerAdapter;
	private ViewPager viewPagerTripTabs;
	private Long currentTripId;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
	        Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_trip_main, container, false);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
	    super.onActivityCreated(savedInstanceState);
	    
	    if(savedInstanceState == null) {
	    	currentTripId = getArguments().getLong(ARG_TRIP_ID);
	    } else {
		    currentTripId = savedInstanceState.getLong(ARG_TRIP_ID);	    	
	    }
	    
	    // Get the fragment's activity
	    FragmentActivity activity = getActivity();

		// Find the ViewPager and set it's adapter
		viewPagerTripTabs = (ViewPager) getView().findViewById(R.id.viewpager_trip_tabs);
		tripTabsStatePagerAdapter = new TripTabsPagerAdapter(activity, activity.getSupportFragmentManager(), currentTripId);
		viewPagerTripTabs.setAdapter(tripTabsStatePagerAdapter);
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
	    super.onSaveInstanceState(outState);
	    
	    outState.putLong(ARG_TRIP_ID, currentTripId);
	}
	
	/**	
	 * This method is use to change the Trip that the {@link TripMainFragment} represents.</br>
	 * IMPORTANT - this method is not for init the trip for the first time!!
	 * @param newTripId The ID of the new trip to initialize
	 */
	public void changeTrip(long newTripId) {
		if(currentTripId != null && currentTripId != newTripId) {
			FragmentActivity activity = getActivity();
			
			// Set the new trip's id
			currentTripId = newTripId;

			// Initialize the ViewPagerAdapter with the selected trip id and initialize it's ViewPager
			tripTabsStatePagerAdapter = new TripTabsPagerAdapter(activity, activity.getSupportFragmentManager(), currentTripId);
			viewPagerTripTabs.setAdapter(tripTabsStatePagerAdapter);
		}
	}
}
